//
//  CPColorUtil.swift
//  ComponentUtils
//
//  Created by wrs on 2018/7/19.
//  Copyright © 2018年 wrs. All rights reserved.
//

import Foundation
import UIKit

extension UIColor {
    public  static func rgb(red: CGFloat, green: CGFloat, blue: CGFloat) -> UIColor
    {
        return UIColor.init(red: red/255, green: green/255, blue: blue/255, alpha: 1)
    }
    public static func color(hex: String, alpha: CGFloat?) -> UIColor
    {
        var colorStr:String = hex.trimmingCharacters(in: NSCharacterSet.whitespacesAndNewlines).uppercased()
        let specs = ["#", "0X"]
        for spec in specs {
            if colorStr.hasPrefix(spec) {
                let subStr: Substring = colorStr.suffix(colorStr.count - spec.count)
                colorStr = String(subStr)
            }
        }
        var red:   CGFloat = 0.0
        var green: CGFloat = 0.0
        var blue:  CGFloat = 0.0
        var alphaValue: CGFloat = 1.0
        
        let scanner = Scanner(string: colorStr)
        var hexValue: CUnsignedLongLong = 0
        if scanner.scanHexInt64(&hexValue) {
            switch (colorStr.count) {
            case 3:
                red   = CGFloat((hexValue & 0xF00) >> 8)       / 15.0
                green = CGFloat((hexValue & 0x0F0) >> 4)       / 15.0
                blue  = CGFloat(hexValue & 0x00F)              / 15.0
            case 4:
                red   = CGFloat((hexValue & 0xF000) >> 12)     / 15.0
                green = CGFloat((hexValue & 0x0F00) >> 8)      / 15.0
                blue  = CGFloat((hexValue & 0x00F0) >> 4)      / 15.0
                alphaValue = CGFloat(hexValue & 0x000F)             / 15.0
            case 6:
                red   = CGFloat((hexValue & 0xFF0000) >> 16)   / 255.0
                green = CGFloat((hexValue & 0x00FF00) >> 8)    / 255.0
                blue  = CGFloat(hexValue & 0x0000FF)           / 255.0
            case 8:
                red   = CGFloat((hexValue & 0xFF000000) >> 24) / 255.0
                green = CGFloat((hexValue & 0x00FF0000) >> 16) / 255.0
                blue  = CGFloat((hexValue & 0x0000FF00) >> 8)  / 255.0
                alphaValue = CGFloat(hexValue & 0x000000FF)         / 255.0
            default:
                return UIColor.clear
            }
        } else {
            return UIColor.clear
        }
        if let tempAlpha = alpha {
            alphaValue = tempAlpha
        }
        return UIColor(red: red, green: green, blue: blue, alpha: alphaValue)
    }
}

